import { List, Button, WingBlank } from 'antd-mobile';
import { Component } from 'react'
import { connect } from 'dva'
import router from 'umi/router';
import { setToken, setTenantid, setRole, getToken, getRole }  from '@/utils/auth'
import StandardForm from '@/components/standardForm'
@connect(({ auth, loading }) => {
  return {
    auth,
  }
})
class Login extends Component {
  constructor(props) {
    super(props)
    this.login = this.login.bind(this)
  }
  componentWillMount() {
    setTenantid(this.props.match.params.tenantid)
    if(getToken()) {
      if(getRole() === 10) {
        router.replace(`/manager/home/worker`)
      } else {
        router.replace(`/worker/details`)
      }
    }
  }
  instantForm = null
  formItems= [
    {
      name: 'phone',
      label: '手机',
      placeholder: '请输入手机',
      options: {
        rules: [{required: true}]
      }
    },
    {
      name: 'password',
      layoutOption: {
        type: 'password'
      },
      label: '密码',
      placeholder: '请输入密码',
      options: {
        rules: [{required: true}]
      }
    }
  ]
  login() {
    const { dispatch, match:{params} } = this.props
    this.instantForm.validateFields((err, values) => {
      if(err) return
      dispatch({
        type: 'auth/login',
        payload: values
      }).then(res => {
        setToken(res.data.token)
        setRole(res.data.role)
        if(res.data.role === 10) {
          router.replace({
            pathname: `/manager/home/worker`
          })
        } else {
          router.replace({
            pathname: `/worker/details`
          })
        }
      })
    })
  }
  render() {
    return (
      <WingBlank style={{paddingTop: '200px'}} >
        <List>
          <StandardForm 
            wrappedComponentRef={el => this.instantForm = el}
            formItems={this.formItems}
          />
        </List>
        <Button 
          style={{margin: '15px 0'}}
          type="primary"
          onClick={this.login}
        >登陆</Button>
      </WingBlank>
    )
  }
}
export default Login